import { useContext, useState } from "react";
import "./App.scss";
import routes from "./router";
import { RouteIdContext } from "./router/context";

function App() {
  const [routeId, setRouteId] = useState(routes[3].id);
  return (
    <RouteIdContext.Provider value={{ routeId, setRouteId }}>
      <div className="frame">
        <header>强化学习演示软件</header>
        <div className="two-column">
          <Aside></Aside>
          <Main></Main>
        </div>
      </div>
    </RouteIdContext.Provider>
  );
}

function Aside() {
  // 获取全局路由中的菜单项
  const menuItems = routes.map((item) => {
    return {
      id: item.id,
      text: item.text,
      icon: item.icon,
    };
  });
  return (
    <aside>
      <Menu items={menuItems}></Menu>
    </aside>
  );
}

interface MenuProps {
  items: MenuItemInfo[];
}
interface MenuItemInfo {
  id: number | string;
  text: string;
  icon: string;
}

function Menu({ items }: MenuProps) {
  const { routeId: activeId } = useContext(RouteIdContext);
  // 遍历items，返回MenuItem组件
  return (
    <>
      {items.map((item) => {
        return (
          <MenuItem
            info={item}
            isActive={item.id === activeId}
            key={item.id}
          ></MenuItem>
        );
      })}
    </>
  );
}

interface MenuItemProps {
  info: MenuItemInfo;
  isActive: boolean;
}
function MenuItem({ info, isActive }: MenuItemProps) {
  const { setRouteId: setActiveId } = useContext(RouteIdContext);
  function handleClick() {
    setActiveId(info.id);
  }
  return (
    <div
      className={`menu-item ${isActive ? "active" : ""}`}
      onClick={handleClick}
    >
      <img alt="" src={`../images/${info.icon}`} />
      {info.text}
    </div>
  );
}

function Main() {
  const { routeId } = useContext(RouteIdContext);
  const route = routes.find((item) => item.id === routeId);
  return <main>{route?.component}</main>;
}

export default App;
